<?php
/**
 * 订单列表
 * User: bgl
 * Date: 2022/8/25
 * Time: 9:35
 */

namespace App\Admin\Controllers\CustomerDelivery;

use App\Admin\Ajax\CustomerDelivery\CustomerOrderAjax;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use App\Models\Product\ProductClassify;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;

class CustomerOrderController extends AdminController
{

    protected $title = '订单查询';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'order_no' => null,
        'status' => null,
        'sku' => null,
        'order_channel' => null,
        'order_type' => null,
        'plat_id' => null,
        'classify_id' => null,
    ];

    protected function grid()
    {
        $areaId = CustomerOrder::getSysAreaOutId();
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['order_no'] = $this->filters['order_no'];
        $filtersBlade['status'] = getOptions(CustomerOrderDetails::$_status, $this->filters['status']);
        $filtersBlade['order_channel'] = getOptions(CustomerOrder::$_shipOrderChannel, $this->filters['order_channel']);
        $filtersBlade['order_type'] = getOptions(CustomerOrder::$_shipOrderType, $this->filters['order_type']);
        $filtersBlade['plat_id'] = getOptions(SysPlat::options(), $this->filters['plat_id']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(), $this->filters['classify_id']);
        $filtersBlade['sku'] = $this->filters['sku'];

        $downloadUrl = '/xqc/customer-delivery/customer-order-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));

        return view('customer-delivery.customer-order.index', compact('paginator','action','filtersBlade','areaId', 'downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = CustomerOrder::query()->orderBy('id', 'DESC');

        foreach ($filters as $field => $filter){
            if(!$filter) continue;
            if($field == 'start_date'){
                $query->where('order_at', '>=', $filter.' 00:00:00');
            }
            if($field == 'end_date'){
                $query->where('order_at', '<=', $filter.' 23:59:59');
            }
            //if($field == 'plat_id'){
            //    $query->where('plat_id', $filter);
            //}
            if($field == 'status'){
                $query->whereHas('detail', function ($query) use($filter){
                    $query->where('status', $filter);
                });
            }
            if($field == 'sku'){
                $query->whereHas('detail.sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->whereHas('detail.sku.classify', function ($query) use($filter){
                    $query->where('id', $filter);
                });
            }
            if(in_array($field,['order_no', 'order_channel', 'order_type', 'plat_id'])){
                $query->where($field, $filter);
            }
        }

        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new CustomerOrderAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');

        $modal = new CustomerOrderAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['订单号', '收货国家', '订单平台', '下单时间','(客户)订单备注', 'SKU', '品类', '产品名称', '下单数量', '申发数量', '申请状态'];
        RExcel::exportCsv('用户订单', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::__getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private function __getData($re){
        foreach ($re as $row){
            $temp = [];
            $temp['order_no'] = $row->order_no ?? '';
            $temp['country'] = $row->receiver->country ?? '';
            $temp['plat_id'] = SysPlat::getSysPlatTitle($row->plat_id);
            $temp['order_at'] = $row->order_at ?? '';
            $temp['order_remarks'] = $row->order_remarks ?? '';

            yield $temp;
            $temp = [];
            foreach ($row->detail as $key => $val){
                $temp['order_no'] = '';
                $temp['country'] = '';
                $temp['plat_id'] = '';
                $temp['order_at'] = '';
                $temp['psku_code'] = $val->sku->psku_code ?? '';
                $temp['classify_title'] = $val->sku->classify->title ?? '';
                $temp['psku_cn'] = $val->sku->psku_cn ?? '';
                $temp['order_num'] = $val->order_num ?? 0;
                $temp['apply_num'] = $val->apply_num ?? 0;
                $temp['status'] = CustomerOrderDetails::$_status[$val->status] ?? '';
                yield $temp;
            }
        }
    }

}
